package com.cz.nongyetongv5.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.EntBean;
import com.cz.nongyetongv5.bean.EntPic;
import com.cz.nongyetongv5.bean.EntProduct;
import com.cz.nongyetongv5.bean.SuperviseCheck;
import com.cz.nongyetongv5.custom.dialog.CustomMyDialog;
import com.cz.nongyetongv5.fragment.EntInfoBaseFragment;
import com.cz.nongyetongv5.fragment.EntInfoFamilyFragment;
import com.cz.nongyetongv5.fragment.EntInfoOperateFragment;
import com.cz.nongyetongv5.fragment.EntInfoOperateNzdFragment;
import com.cz.nongyetongv5.fragment.EntInfoOperateYzhFragment;
import com.cz.nongyetongv5.fragment.EntInfoPhoneFragment;
import com.cz.nongyetongv5.fragment.EntInfoProductFragment;
import com.cz.nongyetongv5.fragment.EntInfoSignatureFragment;
import com.cz.nongyetongv5.fragment.EntInfoTransFragment;
import com.google.gson.Gson;
import com.ronri.common.WaitDialog;
import com.ronri.viewpagerindicator.TitlePageIndicator;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class EntDetailActivity extends FragmentActivity implements View.OnClickListener {


    private RelativeLayout btnBack;
    private TabAdapter adapter;
    private ViewPager viewPager;
    private TextView tv_right;
    private List<Fragment> mFragments;
    private TitlePageIndicator tpiIndicator;
    private LinearLayout ll_bottom;
    private List<String> tabTitles;
    private EntBean entBean;
    private List<EntProduct> entMainProducts;
    private List<EntProduct> entTransProducts;
    private List<EntPic> entPics;
    private int type = 1;
    private TextView tv_title;

    private String add_user;
    private String region_code;

    private TextView tv_pass;
    private TextView tv_refuse;


    private String supervise_id;

    public EntBean getEntBean() {
        return entBean;
    }

    public void setEntBean(EntBean entBean) {
        this.entBean = entBean;
    }

    public List<EntProduct> getEntMainProducts() {
        return entMainProducts;
    }

    public void setEntMainProducts(List<EntProduct> entMainProducts) {
        this.entMainProducts = entMainProducts;
    }

    public List<EntProduct> getEntTransProducts() {
        return entTransProducts;
    }

    public void setEntTransProducts(List<EntProduct> entTransProducts) {
        this.entTransProducts = entTransProducts;
    }

    public List<EntPic> getEntPics() {
        return entPics;
    }

    public void setEntPics(List<EntPic> entPics) {
        this.entPics = entPics;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ent_datail);
        btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        entBean = (EntBean) getIntent().getSerializableExtra("entBean");
        add_user = getIntent().getStringExtra("add_user");
        region_code = getIntent().getStringExtra("region_code");
        supervise_id = getIntent().getStringExtra("supervise_id");
        type = getIntent().getIntExtra("type", 1);
        ll_bottom=findViewById(R.id.ll_bottom);
        tv_title = findViewById(R.id.tv_title);
        if (type == 1) {
            tv_title.setText("生产主体详情");
        } else if (type == 2){
            tv_title.setText("生产主体详情");
            ll_bottom.setVisibility(View.GONE);
        }else {
            tv_title.setText("调查对象详情");
        }
        entMainProducts = new ArrayList<>();
        entTransProducts = new ArrayList<>();
        entPics = new ArrayList<>();

        tv_pass = findViewById(R.id.tv_pass);
        tv_refuse = findViewById(R.id.tv_refuse);
        tv_pass.setOnClickListener(this);
        tv_refuse.setOnClickListener(this);


        if (entBean.getKind().equals("7")) {
            entPics.add(new EntPic(2, 2l, entBean.getCharge_pic()));
            entPics.add(new EntPic(2, 3l, entBean.getId_card_face()));
            entPics.add(new EntPic(2, 4l, entBean.getId_card_back()));
            for (EntPic entPic : entBean.getPhoto()) {
                entPic.setItemType(1);
            }
            entPics.addAll(entBean.getPhoto());
        } else {
            entPics.add(new EntPic(2, 1l, entBean.getBusiness_licence_pic()));
            entPics.add(new EntPic(2, 2l, entBean.getCharge_pic()));
            entPics.add(new EntPic(2, 3l, entBean.getId_card_face()));
            entPics.add(new EntPic(2, 4l, entBean.getId_card_back()));
            for (EntPic entPic : entBean.getPhoto()) {
                entPic.setItemType(1);
            }
            entPics.addAll(entBean.getPhoto());
        }
        //        entPics.addAll(entBean.getPhoto());
        for (EntProduct entProduct : entBean.getProduct()) {
            if (entProduct.getTrans_product().equals("0")) {
                entMainProducts.add(entProduct);
            } else {
                entTransProducts.add(entProduct);
            }
        }
        initTablayout();
        adapter = new TabAdapter(getSupportFragmentManager(), mFragments, tabTitles);
        viewPager = (ViewPager) findViewById(R.id.vpNewListView);
        viewPager.setOffscreenPageLimit(mFragments.size());
        viewPager.setAdapter(adapter);
        tpiIndicator = (TitlePageIndicator) findViewById(R.id.tpiIndicator);
        tpiIndicator.setViewPager(viewPager);
    }


    private void initTablayout() {

        if (entBean.getKind().equals("7")) {//种养殖户
            tabTitles = new ArrayList<>();
            mFragments = new ArrayList<>();
            tabTitles.add("基本信息");
            tabTitles.add("生产经营信息");
            tabTitles.add("主要产品信息");
            mFragments.add(EntInfoBaseFragment.newInstance());
            mFragments.add(EntInfoOperateYzhFragment.newInstance());
            mFragments.add(EntInfoProductFragment.newInstance());
            if (entBean.getIs_transportation().equals("1")) {
                tabTitles.add("收储运信息");
                tabTitles.add("照片信息");
                tabTitles.add("签名信息");
                mFragments.add(EntInfoTransFragment.newInstance());
                mFragments.add(EntInfoPhoneFragment.newInstance());
                mFragments.add(EntInfoSignatureFragment.newInstance());
            } else {
                tabTitles.add("照片信息");
                tabTitles.add("签名信息");
                mFragments.add(EntInfoPhoneFragment.newInstance());
                mFragments.add(EntInfoSignatureFragment.newInstance());
            }
        } else if (entBean.getKind().equals("8")) {//投入品经营店
            tabTitles = new ArrayList<>();
            tabTitles.add("基本信息");
            tabTitles.add("生产经营信息");
            tabTitles.add("照片信息");
            tabTitles.add("签名信息");
            mFragments = new ArrayList<>();
            mFragments.add(EntInfoBaseFragment.newInstance());
            mFragments.add(EntInfoOperateNzdFragment.newInstance());
            mFragments.add(EntInfoPhoneFragment.newInstance());
            mFragments.add(EntInfoSignatureFragment.newInstance());
        } else if (entBean.getKind().equals("6")) {//家庭农场
            tabTitles = new ArrayList<>();
            tabTitles.add("基本信息");
            tabTitles.add("生产经营信息");
            tabTitles.add("主要产品信息");
            mFragments = new ArrayList<>();
            mFragments.add(EntInfoBaseFragment.newInstance());
            mFragments.add(EntInfoFamilyFragment.newInstance());
            mFragments.add(EntInfoProductFragment.newInstance());

            if (entBean.getIs_transportation().equals("1")) {
                tabTitles.add("收储运信息");
                tabTitles.add("照片信息");
                tabTitles.add("签名信息");
                mFragments.add(EntInfoTransFragment.newInstance());
                mFragments.add(EntInfoPhoneFragment.newInstance());
                mFragments.add(EntInfoSignatureFragment.newInstance());
            } else {
                tabTitles.add("照片信息");
                tabTitles.add("签名信息");
                mFragments.add(EntInfoPhoneFragment.newInstance());
                mFragments.add(EntInfoSignatureFragment.newInstance());
            }
        }else {
            tabTitles = new ArrayList<>();
            tabTitles.add("基本信息");
            tabTitles.add("生产经营信息");
            tabTitles.add("主要产品信息");
            mFragments = new ArrayList<>();
            mFragments.add(EntInfoBaseFragment.newInstance());
            mFragments.add(EntInfoOperateFragment.newInstance());
            mFragments.add(EntInfoProductFragment.newInstance());

            if (entBean.getIs_transportation().equals("1")) {
                tabTitles.add("收储运信息");
                tabTitles.add("照片信息");
                tabTitles.add("签名信息");
                mFragments.add(EntInfoTransFragment.newInstance());
                mFragments.add(EntInfoPhoneFragment.newInstance());
                mFragments.add(EntInfoSignatureFragment.newInstance());
            } else {
                tabTitles.add("照片信息");
                tabTitles.add("签名信息");
                mFragments.add(EntInfoPhoneFragment.newInstance());
                mFragments.add(EntInfoSignatureFragment.newInstance());
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 9001:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finish();
                break;
            case R.id.tv_pass:
                if (type == 1) {//生产主体
//                    Intent intent = new Intent(EntDetailActivity.this, DialogActivity.class);
//                    intent.putExtra("add_user", add_user);
//                    intent.putExtra("region_code", region_code);
//                    intent.putExtra("ids", entBean.getId());
//                    intent.putExtra("type", "1");
//                    intent.putExtra("model", "ent");
//                    startActivityForResult(intent, 9001);

                    CustomMyDialog.Builder builder = new CustomMyDialog.Builder(EntDetailActivity.this);
                    builder.setMessage("确认提交？");
                    builder.setPositiveButton("确认提交", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            WaitDialog.ShowDialog(EntDetailActivity.this, "数据加载中...");
                            postCheckEnt("1", String.valueOf(entBean.getE_id()), "", add_user, region_code);
                        }
                    });
                    builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.createNormalDialog().show();
                } else {//示范户
//                    Intent intent = new Intent(EntDetailActivity.this, DialogActivity.class);
                    //                    intent.putExtra("add_user", add_user);
                    //                    intent.putExtra("region_code", region_code);
                    //                    intent.putExtra("ids", supervise_id);
                    //                    intent.putExtra("type", "1");
                    //                    intent.putExtra("model", "supervise");
                    //                    intent.putExtra("status",getIntent().getStringExtra("status"));
                    //                    startActivityForResult(intent, 9001);
                    CustomMyDialog.Builder builder = new CustomMyDialog.Builder(EntDetailActivity.this);
                    builder.setMessage("确认提交？");
                    builder.setPositiveButton("确认提交", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            List<SuperviseCheck> superviseChecks=new ArrayList<>();
                            superviseChecks.add(new SuperviseCheck(supervise_id,getIntent().getStringExtra("status")));
                            WaitDialog.ShowDialog(EntDetailActivity.this, "数据加载中...");
                            postCheckSupervise("", add_user, region_code,"1",new Gson().toJson(superviseChecks));
                        }
                    });
                    builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.createNormalDialog().show();
                }
                break;
            case R.id.tv_refuse:
                if (type == 1) {//生产主体
                    Intent intent = new Intent(EntDetailActivity.this, DialogActivity.class);
                    intent.putExtra("add_user", add_user);
                    intent.putExtra("region_code", region_code);
                    intent.putExtra("ids", String.valueOf(entBean.getE_id()));
                    intent.putExtra("type", "2");
                    intent.putExtra("model", "ent");
                    startActivityForResult(intent, 9001);
                } else {//示范户
                    List<SuperviseCheck> superviseChecks=new ArrayList<>();
                    superviseChecks.add(new SuperviseCheck(supervise_id,getIntent().getStringExtra("status")));
                    Intent intent = new Intent(EntDetailActivity.this, DialogActivity.class);
                    intent.putExtra("add_user", add_user);
                    intent.putExtra("region_code", region_code);
                    intent.putExtra("ids", new Gson().toJson(superviseChecks));
                    intent.putExtra("type", "2");
                    intent.putExtra("model", "supervise");
//                    intent.putExtra("status",getIntent().getStringExtra("status"));
                    startActivityForResult(intent, 9001);
                }
                break;
                default:
                    break;
        }
    }

    /**
     * 适配器代码
     */
    class TabAdapter extends FragmentStatePagerAdapter {
        public List<Fragment> list;
        private List<String> titles;

        public TabAdapter(FragmentManager fm, List<Fragment> list, List<String> titles) {
            super(fm);
            this.list = list;
            this.titles = titles;
        }

        @Override
        public Fragment getItem(int position) {
            //            EntListFragment fragment = EntListFragment.newInstance();
            //            Bundle args = new Bundle();
            //            args.putInt("type", 0);
            //            args.putString("args", szTabTitle[position]);
            //            args.putInt("single",position+1);
            //            fragment.setArguments(args);
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }


    void postCheckEnt(String type, String ids, final String reason, String add_user, String region_code) {
        OkHttpUtils
                .post()
                .url(InitApplication.newUrl + "ent/checkEnt.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("type", type)
                .addParams("ids", ids)
                .addParams("reason", "")
                .addParams("add_user", add_user)
                .addParams("region_code", region_code)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(EntDetailActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.optInt("code");
                            if (code == 0) {
                                Toast.makeText(EntDetailActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                                setResult(Activity.RESULT_OK);
                                finish();
                            } else {
                                Toast.makeText(EntDetailActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }



    void postCheckSupervise(String reason, String add_user, String region_code, String type, String json) {
        OkHttpUtils
                .post()
                .url(InitApplication.newUrl + "supervise/checkSuperviseList.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("reason", reason)
                .addParams("add_user", add_user)
                .addParams("region_code", region_code)
                .addParams("type", type)
                .addParams("json", json)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(EntDetailActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.optInt("code");
                            if (code == 0) {
                                Toast.makeText(EntDetailActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                                setResult(Activity.RESULT_OK);
                                finish();
                            } else {
                                Toast.makeText(EntDetailActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


//    void postCheckSupervise(String ids, String reason, String add_user, String region_code, String type, String status) {
//        OkHttpUtils
//                .post()
//                .url(InitApplication.newUrl + "supervise/checkSupervise.json")
//                .addParams("addFrom", "1")
//                .addParams("addMark", "android")
//                .addParams("ids", ids)
//                .addParams("reason", "")
//                .addParams("add_user", add_user)
//                .addParams("region_code", region_code)
//                .addParams("type", type)
//                .addParams("status", status)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        Toast.makeText(EntDetailActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            int code = jsonObject.optInt("code");
//                            if (code == 0) {
//                                Toast.makeText(EntDetailActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
//                                setResult(Activity.RESULT_OK);
//                                finish();
//                            } else {
//                                Toast.makeText(EntDetailActivity.this, "提交失败，稍后再试", Toast.LENGTH_SHORT).show();
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
//    }
}
